<template>
  <PageSearch
    :search-form-config="searchFormConfig"
    @queryClick="handleQueryClick"
    @resetClick="handleResetClick"
  ></PageSearch>
  <PageContent
    ref="pageContentRef"
    :content-table-config="contentTableConfig"
    @createBtnClick="handleCreateClick"
    @editBtnClick="handleEditClick"
    pageName="role"
  ></PageContent>
  <PageModal
    ref="pageModal"
    :defaultInfo="defaultInfo"
    :otherInfo="otherInfo"
    :modalConfig="modalConfig"
    pageName="role"
  >
    <div class="tree">
      <el-tree
        ref="elTreeRef"
        :data="menus"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
        @check="handleCheckChange"
      ></el-tree>
    </div>
  </PageModal>
</template>

<script setup lang="ts">
import { computed, ref, nextTick } from 'vue'
import { useStore } from '@/store'

import { ElTree } from 'element-plus'

import PageSearch from '@/components/PageSearch'
import PageContent from '@/components/PageContent'
import PageModal from '@/components/PageModal'

import { searchFormConfig } from './config/search.config'
import { contentTableConfig } from './config/content.config'
import { modalConfig } from './config/modal.config'

import { usePageSearch } from '@/hooks/usePageSearch'
import { usePageModal } from '@/hooks/usePageModal'

import { menuMapLeafKeys } from '@/utils/mapMenus'

const elTreeRef = ref<InstanceType<typeof ElTree>>()
const editCallback = (item: any) => {
  const leafKeys = menuMapLeafKeys(item.menuList)
  nextTick(() => {
    elTreeRef.value?.setCheckedKeys(leafKeys, false)
  })
}

const [pageContentRef, handleQueryClick, handleResetClick] = usePageSearch()
const [defaultInfo, pageModal, handleCreateClick, handleEditClick] = usePageModal(undefined, editCallback)

const store = useStore()
const menus = computed(() => store.state.entireMenu)

const otherInfo = ref({})
const handleCheckChange = (data1: any, data2: any) => {
  const checkedKeys = data2.checkedKeys
  const halfCheckedKeys = data2.halfCheckedKeys
  const menuList = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuList }
}
</script>

<style scoped lang="less">
.tree {
  margin-left: 25px;
}
</style>
